<template>
	<view class="chatInterface" id="message-scroll">
		<!-- <image class="group-icon" src="/static/images/group-icon.png" @click="showMembers" /> -->
		<scroll-view scroll-y class="scroll-view" @click="closeDropdown"
			style="position:relative;height:95vh;padding-bottom: 50rpx" :scroll-into-view="viewIndex"
			@scroll="scrollView" :refresher-enabled="!allHistoryLoaded" :refresher-triggered="triggered"
			refresher-background="#e9e9e9" @refresherrefresh="refresh">
			<!-- 操作提示框 -->
			<view class="tooltips" v-if="clientY > 200" :class="isShowTip ? 'tooltips-active': 'tooltips-inactive'"
				:style="isMine ? {'top': top + 'px','right': '50rpx'} : {'top': top + 'px','left': '50rpx'}">
				<view class="opt-item" @click.stop="copyMessage()" v-if="currentMessage.message_type == 'text'">
					<i class="icon icon-fuzhi"></i>
					<text class="opt-item-text">{{ $t('chat.chat_copy') }}</text>
				</view>
				<view class="opt-item" @click.stop="transmitMessage()">
					<i class="icon">&#xe6cf;</i>
					<text class="opt-item-text">{{ $t('chat.chat_forward') }}</text>
				</view>
				<view class="opt-item" @click.stop="deleteSingleMessage">
					<i class="icon icon-shanchutianchong"></i>
					<text class="opt-item-text">{{ $t('chat.chat_delete') }}</text>
				</view>
				<view class="opt-item" @click.stop="showCheckBox">
					<i class="icon icon-duoxuan-04"></i>
					<text class="opt-item-text">{{ $t('chat.chat_mul_choose') }}</text>
				</view>
				<view class="opt-item" v-if="actionPopup.recallable" @click.stop="recallMessage">
					<i class="icon icon-chehuisekuai"></i>
					<text class="opt-item-text">{{ $t('chat.chat_recall')}}</text>
				</view>
				<view class="opt-item" @click.stop="Translate(1)" v-if="currentMessage.message_type == 'text'">
					<i class="icon icon-business-translate"></i>
					<text class="opt-item-text">{{$t('chat.english')}}→{{ $t('chat.chinese')}}</text>
				</view>
				<view class="opt-item" @click.stop="Translate(3)" v-if="currentMessage.message_type == 'text'">
					<i class="icon icon-business-translate"></i>
					<text class="opt-item-text">{{ $t('chat.chinese')}}→{{ $t('chat.english')}}</text>
				</view>
				<view class="opt-item" @click.stop="Translate(2)" v-if="currentMessage.message_type == 'text'">
					<i class="icon icon-business-translate"></i>
					<text class="opt-item-text">{{ $t('chat.ru')}}→{{ $t('chat.chinese')}}</text>
				</view>
				<view class="opt-item" @click.stop="Translate(4)" v-if="currentMessage.message_type == 'text'">
					<i class="icon icon-business-translate"></i>
					<text class="opt-item-text">{{ $t('chat.chinese') }}→{{ $t('chat.ru') }}</text>
				</view>
				<view class="triangle1" :style="isMine ? {'right': '70rpx'}: {'left': '54rpx'}"></view>
			</view>
			<view class="tooltips" v-if="clientY <= 200" :class="isShowTip ? 'tooltips-active': 'tooltips-inactive'"
				:style="clientY > 0 ? (isMine ? {'top': top + 200 + 'px','right': '50rpx'} : {'top': top + 200+'px','left': '50rpx'}) :(isMine ? {'top': top + 'px','right': '50rpx'} : {'top': top + 'px','left': '50rpx'})">
				<view class="opt-item" @click.stop="copyMessage()" v-if="currentMessage.message_type == 'text'">
					<i class="icon icon-fuzhi"></i>
					<text class="opt-item-text">{{ $t('chat.chat_copy') }}</text>
				</view>
				<view class="opt-item" @click.stop="transmitMessage()">
					<i class="icon">&#xe6cf;</i>
					<text class="opt-item-text">{{ $t('chat.chat_forward') }}</text>
				</view>
				<view class="opt-item" @click.stop="deleteSingleMessage">
					<i class="icon icon-shanchutianchong"></i>
					<text class="opt-item-text">{{ $t('chat.chat_delete') }}</text>
				</view>
				<view class="opt-item" @click.stop="showCheckBox">
					<i class="icon icon-duoxuan-04"></i>
					<text class="opt-item-text">{{ $t('chat.chat_mul_choose') }}</text>
				</view>
				<view class="opt-item" v-if="actionPopup.recallable" @click.stop="recallMessage">
					<i class="icon icon-chehuisekuai"></i>
					<text class="opt-item-text">{{ $t('chat.chat_recall')}}</text>
				</view>
				<view class="opt-item" @click.stop="Translate(1)" v-if="currentMessage.message_type == 'text'">
					<i class="icon icon-business-translate"></i>
					<text class="opt-item-text">{{$t('chat.english')}}→{{ $t('chat.chinese')}}</text>
				</view>
				<view class="opt-item" @click.stop="Translate(3)" v-if="currentMessage.message_type == 'text'">
					<i class="icon icon-business-translate"></i>
					<text class="opt-item-text">{{ $t('chat.chinese')}}→{{ $t('chat.english')}}</text>
				</view>
				<view class="opt-item" @click.stop="Translate(2)" v-if="currentMessage.message_type == 'text'">
					<i class="icon icon-business-translate"></i>
					<text class="opt-item-text">{{ $t('chat.ru')}}→{{ $t('chat.chinese')}}</text>
				</view>
				<view class="opt-item" @click.stop="Translate(4)" v-if="currentMessage.message_type == 'text'">
					<i class="icon icon-business-translate"></i>
					<text class="opt-item-text">{{ $t('chat.chinese') }}→{{ $t('chat.ru') }}</text>
				</view>
				<view class="triangle2" :style="isMine ? {'right': '70rpx'}: {'left': '54rpx'}"></view>
			</view>
			<view class="all-history-loaded">
				{{allHistoryLoaded ? $t('chat.chat_no_more_history') : $t('chat.chat_down_get_history')}}
			</view>
			<checkbox-group @change="selectMessages">
				<view v-for="(message,index) in messages" :key="message.message_id">
					<!--时间显示，类似于微信，隔5分钟不发言，才显示时间-->
					<view class="time-lag">
						{{renderMessageDate(message, index)}}
					</view>
					<view class="message-recalled" v-if="message.message_recalled == 1">
						<view v-if="message.sender_id != currentUser.uid">
							{{message.sender_name}}{{$t('chat.chat_recall_message')}}
						</view>
						<view v-else class="message-recalled-self">
							<view>{{$t('chat.chat_recall_message_self')}}</view>
							<span v-if="message.message_type === 'text' && Date.now()-message.timestamp< 60 * 1000 "
								@click.stop="editRecalledMessage(message.payload_text)">{{$t('chat.chat_reedit')}}</span>
						</view>
					</view>
					<view class="message-item" v-else>
						<view class="message-item-checkbox">
							<checkbox v-show="messageSelector.visible && message.message_status !== 'sending'"
								:value="message.message_id" :checked="messageSelector.messages.includes(message)" />
						</view>
						<view class="message-item-content" :class="{'self' : message.sender_id ==  currentUser.uid}">
							<view class="avatar">
								<image @click.stop="go2User(message.sender_id)"
									:src="groupMemberAvatar(message.sender_avatar, message.sender_id)"
									style="border-radius:16rpx"></image>
							</view>
							<view @longpress="longPress(message, index)" @touchend="touchEnd" @touchmove="touchMove"
								class="content" :id="'content' + message.message_id">
								<view v-if="message.sender_id==currentUser.uid"
									style="text-align:right;font-size:28rpx;color:#6E7172">
									{{message.sender_name}}
								</view>
								<view v-if="message.sender_id!=currentUser.uid"
									style="text-align:left;font-size:28rpx;color:#6E7172">
									{{sendMessageNickname(message)}}
								</view>
								<view class="message-payload">
									<b class="pending" v-if="message.message_status === 'sending'"></b>
									<b class="send-fail" v-if="message.message_status === 'fail'"></b>
									<view v-if="message.message_type === 'text'">
										<view v-html="renderTextMessage(message)">
										</view>
										<span class="text-content" style="border-top-left-radius: 0 ;border-top-right-radius: 0;
										 border-top:1px solid #cccccc;margin-top: -2rpx;"
											v-if="dicttext[message.message_id]">{{dicttext[message.message_id]}}</span>
									</view>
									<image class="image-content" v-if="message.message_type === 'image'"
										:src="messageImageUrl(message.payload_url)" :data-url="message.payload_url"
										@click.stop="previewOpen(message.payload_url)" mode="widthFix"></image>
									<view class="video-snapshot" v-if="message.message_type === 'video'"
										:data-url="message.video_url" @click.stop="previewOpen(message.video_url)">
										<image :src="messageImageUrl(message.thumbnail_url)" mode="aspectFit"></image>
										<view class="video-play-icon"></view>
									</view>
									<GoEasyAudioPlayer v-if="message.message_type ==='audio'" :src="message.payload_url"
										:duration="message.payload_duration" />
									<TUI-FileMessage v-if="message.message_type === 'file'" :message="message">
									</TUI-FileMessage>
									<image class="image-content" v-if="message.message_type === 'transmitImage'"
										:src="message.payload_path" :data-url="message.payload_path"
										@click.stop="previewOpen(message.payload_path)" mode="widthFix"></image>
									<view class="video-snapshot" v-if="message.message_type === 'transmitvideo'"
										:data-url="message.payload_video_url"
										@click.stop="previewOpen(message.payload_video_url)">
										<image :src="message.payload_thumbnai_url" mode="aspectFit"></image>
										<view class="video-play-icon"></view>
									</view>
									<view class="custom-message" v-if="message.message_type === 'order'">
										<view class="title">
											<image src="../../../../static/images/order.png"></image>
											<text>自定义消息</text>
										</view>
										<view class="custom-message-item">编号：{{message.payload.number}}</view>
										<view class="custom-message-item">商品: {{message.payload.goods}}</view>
										<view class="custom-message-item">金额: {{message.payload.price}}</view>
									</view>
									<view class="transmit-box" v-else-if="message.message_type === 'mergeTransmit'"
										@click.stop="showAllData(message)">
										{{getmess(message)}}
										<span class="transmit-box-title">合并转发聊天记录</span>
										<view class="transmit-box-content">
											<view v-for="(message1,index1) in msgarr2" :key="message1.message_id">
												<view v-if="message1.message_type === 'text'"
													v-html="transmitRenderTextMessage(message1)">
												</view>
												<text
													v-else-if="message1.message_type === 'transmitImage'">[{{ $t('chat.chat_image_message') }}]</text>
												<text
													v-else-if="message1.message_type === 'image'">[{{ $t('chat.chat_image_message') }}]</text>
												<text
													v-else-if="message1.message_type === 'video'">[{{ $t('chat.chat_video_message') }}]</text>
												<text
													v-else-if="message1.message_type === 'transmitvideo'">[{{ $t('chat.chat_video_message') }}]</text>
											</view>
										</view>
										<view class="transmit-box-footer">查看<text>{{msgarr2.length}}</text>条合并转发消息
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>

				<!-- 可滚动到底部的view标签 -->
				<view v-show="scrollToBottom" :id="'im_'+messages.length" style="margin-top:400rpx"></view>
			</checkbox-group>
		</scroll-view>
		<yt-uploads ref="uploads" :options="option" @selected="selectedHandler">
		</yt-uploads>
		<view class="action-box" v-if="!videoPlayer.visible && !messageSelector.visible">
			<view class="action-top" style="position: relative" :style="{'height': height + 60+'rpx'}">
				<view :class="[audio.visible ? 'icon icon-jianpan':'icon icon-yuyin-']"
					@click.stop="switchAudioKeyboard">
				</view>
				<view class="record-input" @touchmove="onRecordCancel" @touchstart="onRecordStart"
					@touchend="onRecordEnd" v-if="audio.visible">
					{{audio.recording ? $t('chat.chat_release_send') : $t('chat.chat_hold_record')}}
				</view>
				<view class="message-input" v-else :style="{'height': height + 32 + 'rpx'}">
					<!-- GoEasyIM最大支持3k的文本消息，如需发送长文本，需调整输入框maxlength值 -->
					<textarea ref="textarea" name="" id="" cols="44" rows="20" :auto-height="true" cursor-spacing="24"
						placeholder="" v-model="content" class="textarea-box" maxlength="-1"
						@focus="messageInputFocusin" @linechange="getHeight" @input="inputContent" auto-height="true"
						@blur="textblur"></textarea>
				</view>
				<view class="icon icon-biaoqing1" @click.stop="showEmoji"></view>
				<view class="file-icon more-icon"
					style="width:76rpx;height:72rpx;position:absolute;bottom:18rpx;right:40rpx"
					@click.stop="showOtherTypesMessagePanel" v-show="changeSendMode == 'add'"></view>
				<span class="send-message-btn" @click.stop="createTextMessage"
					v-show="changeSendMode == 'send'">{{$t('chat.chat_send')}}</span>
			</view>
			<!-- 展示表情包 -->
			<view v-if="emoji.visible">
				<view class="TUI-Emoji-area">
					<TUI-Emoji @enterEmoji="appendMessage"></TUI-Emoji>
				</view>
				<i class="icon icon-qingchu" @click="deleteEmojiMessage"></i>
			</view>
			<!-- <view class="action-bottom action-bottom-emoji" v-if="emoji.visible">
        <image class="emoji-item" v-for="(emojiItem, key, index) in emoji.map" :key="index"
          :src="emoji.url + emojiItem" @click.stop="chooseEmoji(key)"></image>
      </view> -->
			<!--其他类型消息面板-->
			<view class="action-bottom" v-show="otherTypesMessagePanelVisible" style="position:relative">
				<view class="action-item" @click.stop="createImageMessage">
					<view class="icon icon-xiangce"></view>
					<text class="action-item-text">{{$t('chat.album')}}</text>
				</view>
				<view class="action-item" @click.stop="createVideoMessage">
					<view class="icon icon-31paishexuanzhong"></view>
					<text class="action-item-text">{{$t('chat.shot')}}</text>
				</view>
				<view class="action-item">
					<view class="icon icon-wenjianjiatianjia" @tap="selectFileHandler"></view>
					<text class="action-item-text">{{$t('chat.file')}}</text>
				</view>

				<!-- 	<view class="more-item" @click.stop="createFileMessage">
          <image src="../../../static/images/shipin.png"></image>
          <text>文件</text>
        </view> -->
			</view>
		</view>

		<view class="action-popup" @touchmove.stop.prevent v-if="actionPopup.visible">
			<view class="layer"></view>
			<view class="action-box">
				<view class="action-item" @click.stop="deleteSingleMessage">{{$t('chat.chat_delete')}}</view>
				<view class="action-item" v-if="actionPopup.recallable" @click.stop="recallMessage">{{$t('chat.chat_recall')}}
				</view>
				<view class="action-item" @click.stop="showCheckBox">{{$t('chat.chat_mul_choose')}}</view>
				<view class="action-item" v-if="messageSelector.messages[0].type === 'text'"
					@click.stop="copyMessage()">
					{{$t('chat.chat_copy')}}
				</view>
				<view class="action-item" @click.stop="transmitMessage()">{{ $t('chat.chat_forward') }}</view>
				<view class="action-item" @click.stop="actionPopup.visible = false">{{$t('chat.chat_cancel')}}</view>
			</view>
		</view>
		<view class="messageSelector-box" v-if="messageSelector.visible">
			<i class="icon icon-31zhuanfa mul-btn" @click.stop="transmitMultipleMessages"><label
					class="u-font-32 u-m-l-10">{{ $t('chat.transfer')}}</label></i>
			<i class="icon icon-shanchu mul-btn" @click.stop="deleteMultipleMessages"><label
					class="u-font-32 u-m-l-10">{{ $t('chat.btn_del') }}</label></i>
		</view>
		<view class="record-loading" v-if="audio.recording"></view>
		<video v-if="videoPlayer.visible" :src="videoPlayer.url" id="videoPlayer"
			@fullscreenchange="onVideoFullScreenChange"></video>
		<CustomMessage v-if="customMessageFormVisible" @createCustomMessage="createCustomMessage"
			@closeCustomMessageForm="closeCustomMessageForm"></CustomMessage>
		<previewImage ref="previewImage" :opacity="0.8" :circular="true" :imgs="imageArr"></previewImage>
	</view>
</template>

<script>
	import pageMixin from '@/utils/pageMixin';
	import GoEasyAudioPlayer from '../../../../components/GoEasyAudioPlayer/GoEasyAudioPlayer';
	import CustomMessage from '../../../../components/CustomMessage/CustomMessage';
	import EmojiDecoder from '../../../../commen/base/EmojiDecoder';
	import TUIEmoji from '../../../../commen/tui-chat/message-elements/emoji/index';
	// import TUIFileMessage from '../../../../commen/tui-chat/message-elements/file-message/index';
	import previewImage from '@/components/kxj-previewImage/kxj-previewImage.vue'; //引用插件
	import {
		db
	} from "@/utils/sqlite";
	import sqliteSQL from "@/utils/sqliteSQL";
  // import ytUploads from "@/components/yt-uploads/yt-uploads.vue"
  const recorderManager = uni.getRecorderManager();
	export default {
		mixins: [pageMixin],
		name: 'groupChat',
		components: {
			GoEasyAudioPlayer,
			CustomMessage,
			TUIEmoji,
			// TUIFileMessage,
			previewImage
		},
		data() {
			return {
				groupId: 0,
                timeOut:null,
				//聊天文本框
				content: '',
				group: null,
				currentUser: null,
				//群成员
				groupMembers: {},
				groupMemberDict: [],
				//消息记录
				messages: [],
				goeasyMessages: [],
				dicttext: [],
				//是否加载完所有历史消息
				allHistoryLoaded: false,
				//定义表情列表
				emoji: {
					visible: false,
					decoder: new EmojiDecoder(),
				},
				//是否展示‘其他消息类型面板’
				otherTypesMessagePanelVisible: false,
				audio: {
					startTime: null,
					//语音录音中
					recording: false,
					//录音按钮展示
					visible: false
				},
				videoPlayer: {
					visible: false,
					url: '',
					context: null
				},
				// 展示自定义消息框
				customMessageFormVisible: false,

				// 展示消息删除弹出框
				actionPopup: {
					visible: false,
					message: null,
					recallable: false,
					index: null,
				},
				// 消息选择
				messageSelector: {
					visible: false,
					messages: []
				},

				//项目ID
				pid: 0,
				token: '',
				//服务历史消息
				idx: 1,
				count: 0,
				RecordCancel: 0,
				startX: 0,
				startY: 0,
				endX: 0,
				endY: 0,
				height: 80,
				textHeight: 80,
				tabIndex: 0,
				ifLongtap: true,

				pageIdx: 1,
				pageSize: 10,
				lastMessageTimeStamp: null,
				lastMessageTime: 0,
				mergeDataDict: [],
				changeSendMode: 'add',
				top: 0,
				scrollTop: 0,
				isShowTip: false, //是否显示操作菜单
				isMine: false, //是否是我发的消息
				currentMessage: {},
				triggered: false,
				viewIndex: '',
				imageArr: [], //图片预览数组
				clientY: 0, //消息距离顶部的可视距离
				scrollToBottom: false,
				cursorStart: 0, //光标输入位置
				selectList: [],
				//这里是上传文件配置
				option: {
					// 选则图片或者视频 图片:0 视频:1 全文件:2
					type: 2,
					// 上传文件的key 后台根据这个key取得文件
					name: 'file',
					// header请求头
					headers: {},
					// 额外的传输数据
					data: {},
					// 上传的地址
					host: "",
					// 选择数量
					count: 5,
					// 搞了这个方法在上传之前调用一定要返回true不然不会执行上传
					beforeUpload: (ret) => {
						return true
					},
					// 创建成功钩子
					created: (ret) => {},
					// 是否自动上传
					autoUpload: true
				},
				// 选择文件后是否立即自动上传，true=选择后立即上传
				instantly: false,
				// 必传宽高且宽高应与slot宽高保持一致
				width: '60rpx',
				heightFile: '180rpx',
				// 限制允许上传的格式，空串=不限制，默认为空
				formats: '',
				// 文件上传大小限制
				size: 30,
				// 文件回显列表
				files: new Map(),
				// 微信小程序Map对象for循环不显示，所以转成普通数组，不要问为什么，我也不知道
				wxFiles: [],
				// 是否打印日志
				debug: true,
				//上传文件配置结束

			}
		},
		watch: {
			messages(newval) {
				this.imageArr = []
				newval.forEach(item => {
					console.log(item)
					let url = ''
					let cover = ''
					switch (item.message_type) {
						case 'transmitImage':
							url = item.payload_path;
							break;
						case 'image':
							url = item.payload_url;
							break;
						case 'transmitvideo':
							url = item.payload_video_url;
							cover = item.payload_thumbnai_url
							break;
						case 'video':
							url = item.video_url;
							cover = item.thumbnail_url
							break;
						default:
							break;
					}
					if (url != '') {
						this.imageArr.push({
							type: item.message_type,
							url: url,
							cover: cover
						})
					}
				})
				console.log('轮播图片数据', this.imageArr)
			}
		},
		onReady() {
			this.videoPlayer.context = uni.createVideoContext('videoPlayer', this);
			this.option = {
				url: 'https://www.example.com/upload', //替换为你的接口地址
				name: 'file', // 附件key
				//根据你接口需求自定义请求头
				header: {
					'Authorization': 'token'
				},
				//根据你接口需求自定义body参数
				formData: {
					'orderId': 1000
				}
			};

			// 测试更新参数
			// setTimeout(() => {
			// 	console.log('----演示动态更新参数-----');
			// 	this.$refs.lsjUpload.setData('formData.orderId', '20000');
			// }, 2000)
		},
		onShow() {
			this.otherTypesMessagePanelVisible = false;
			this.emoji.visible = false;
		},
		computed: {
			i18n() {
				return this.$t('chat')
			},
		},
		onLoad(options) {

			uni.showLoading()
			
			//聊天对象
			let groupId = options.to || 0;
			let groupName = options.conversation_name || ''
			this.groupId = groupId;
			this.pid = options.pid || 0;
			this.lastMessageTime = options.lastMessageTime || 0
			this.currentUser = this.vuex_user;
			if (groupName != '') {
				uni.setNavigationBarTitle({
					title: groupName
				});
			}

			//监听goeasy消息
			this.loadHistoryMessage();
			this.initialGoEasyListeners();

			//打开SQLite数据库
			let dbname = sqliteSQL.db.dbName
			let path = '_doc/' + this.vuex_user.uid + '.db'
			let isOpen = db.isOpenDB(dbname, path)
			if (!isOpen) {
				plus.sqlite.openDatabase({
					name: dbname,
					path: path,
					success: function(res) {
						console.log("打开成功")
					},
					fail: function(e) {
						console.log('failed: ' + JSON.stringify(e))
					}
				});
			}

			//从服务器获取最新的群信息
			this.$http.get('/mgr/user/group/member/list/data', {
				gid: groupId
			}).then(res => {
				this.group = res.groupInfo;
				for (let i = 0; i < res.groupMemberList.length; i++) {
					this.groupMemberDict[res.groupMemberList[i].UserId] = res.groupMemberList[i]
				}
				uni.setNavigationBarTitle({
					title: res.groupInfo.GroupName + '（' + Object.keys(res.groupMemberList).length + '）'
				});
			});

			this.connectGoEasy();
			let that = this;
			setTimeout(function() {
				that.getSQLiteMessage(groupId, true)
				// 录音监听器
				that.initRecorderListeners();
			}, 500);
			that.TranslateNew() // 获取翻译接口token
		},
		onPullDownRefresh(e) {
			this.getSQLiteMessage(this.groupId, false)
		},
		onUnload() {

			//退出聊天页面之前，清空监听器
			this.goEasy.im.on(this.GoEasy.IM_EVENT.GROUP_MESSAGE_RECEIVED, () => {});
			this.goEasy.im.on(this.GoEasy.IM_EVENT.MESSAGE_DELETED, () => {});
		},
		methods: {
			refresh() {
				if (this.allHistoryLoaded) {
					this.setData({
						allHistoryLoaded: true,
						triggered: false
					});
				}
				this.triggered = true;
				this.getSQLiteMessage(this.groupId, false)
				setTimeout(() => {
					this.setData({
						triggered: false
					});
				}, 2000);
			},
			getSQLiteMessage(groupId, scrollToBottom) {
				let that = this
				let dbname = sqliteSQL.db.dbName
				let path = '_doc/' + this.vuex_user.uid + '.db'
				let lastMessageTimeStamp = this.lastMessageTimeStamp;
				let selectSql = ''
				if (lastMessageTimeStamp === null) {
					selectSql =
						`SELECT * FROM im_conversation_message WHERE receiver_id='${groupId}' ORDER BY timestamp DESC LIMIT ${this.pageSize}`
				} else {
					selectSql =
						"SELECT * FROM im_conversation_message WHERE receiver_id='" + groupId + "' AND `timestamp` < " +
						lastMessageTimeStamp + " ORDER BY timestamp DESC  LIMIT " + this.pageSize
				}

				console.log("lastMessageTimeStamp", lastMessageTimeStamp)
				console.log("selectSql", selectSql)
				plus.sqlite.selectSql({
					name: dbname,
					sql: selectSql,
					success: (res) => {
						if (res.length == 0) {
							that.syncGoeasyMessage(groupId, scrollToBottom)
						} else {
							if (lastMessageTimeStamp === null) {
								that.lastMessageTimeStamp = res[res.length - 1].timestamp
								res.sort(function(a, b) {
									return a.timestamp - b.timestamp
								})
							} else {
								that.lastMessageTimeStamp = res[res.length - 1].timestamp
								res.sort(function(a, b) {
									return a.timestamp - b.timestamp
								})
							}
							//补充数据
							for (let i = 0; i < res.length; i++) {
								let mergeId = res[i].message_id
								plus.sqlite.selectSql({
									name: dbname,
									sql: `SELECT * FROM im_merge_message WHERE receiver_id='${groupId}' AND merge_id='${mergeId}'`,
									success: (result) => {
										uni.hideLoading()
										let mergeDataDict = []
										for (let k = 0; k < result.length; k++) {
											mergeDataDict[result[k].merge_id] = k
										}
										that.mergeDataDict = mergeDataDict
										console.log("出来了", result)
										res[i].merge_data = result
									},
									fail: function(e) {
										console.log("补充的消息", e)
									}
								})
							}
							that.messages = res.concat(that.messages);
							setTimeout(() => {
								that.viewIndex = "im_" + that.messages.length;
							}, 100)

							that.scrollToBottom = scrollToBottom
							if (scrollToBottom) {
								that.scrollToBottom();
								//收到的消息设置为已读
								that.markPrivateMessageAsRead();
							}
						}
					},
					fail: function(e) {
						console.log("获取消息列表的", e)
					}
				})
			},
			//评论输入框失去焦点的时候触发以此来保存光标位置
			textblur(e) {
				this.cursorStart = e.target.cursor
			},
			syncGoeasyMessage(groupId, scrollToBottom) {
				let that = this
				let lastMessageTimeStamp = this.lastMessageTimeStamp;
				this.goEasy.im.history({
					groupId: groupId,
					lastTimestamp: lastMessageTimeStamp,
					limit: 10,
					onSuccess: (result) => {
						let messages = result.content;
						if (messages.length === 0) {
							console.log("没消息了，没消息了")
							//检查是否有服务消息未读
							this.getServerMessageList();
						} else {
							uni.stopPullDownRefresh();

							console.log("获取新的消息了", messages)

							let insertData = []
							let messageData = []
							for (let i = 0; i < messages.length; i++) {

								let messageId = messages[i].messageId
								let video = messages[i].payload.video || {}
								let thumbnail = messages[i].payload.thumbnail || {}
								let senderData = messages[i].senderData || {}
								let payloadUrl = messages[i].payload.url || ''
								let videoUrl = video.url || ''
								let thumbnailUrl = thumbnail.url || ''
								let payload = messages[i].payload || {}
								if (messages[i].type === 'mergeTransmit') {

									//补充合并消息
									payload = JSON.parse(payload)
									this.saveMergeMessage(groupId, messageId, payload)
								}

								//下载图片、视频、音频到本地
								this.downloadMessageFile(payloadUrl, messageId, 'payload_url')
								this.downloadMessageFile(videoUrl, messageId, 'video_url')
								this.downloadMessageFile(thumbnailUrl, messageId, 'thumbnail_url')
								this.downloadMessageFile(senderData.avatar || '', messageId, 'sender_avatar')
								this.downloadMessageFile(messages[i].payload.videoUrl || '', messageId,
									'payload_video_url')
								this.downloadMessageFile(messages[i].payload.thumbnailUrl || '', messageId,
									'payload_thumbnai_url')
								this.downloadMessageFile(messages[i].payload.path || '', messageId,
									'payload_path')

								//组装插入数据
								let insert = {
									'message_id': messages[i].messageId,
									'receiver_id': groupId,
									'sender_id': messages[i].senderId,
									'sender_name': senderData.name || '',
									'sender_avatar': senderData.avatar || '',
									'timestamp': messages[i].timestamp,
									'message_type': messages[i].type,
									'message_recalled': messages[i].recalled ? 1 : 0,
									'message_status': messages[i].status,
									'message_read': messages[i].read ? 1 : 0,
									'payload_text': messages[i].payload.text || '',
									'payload_name': messages[i].payload.name || '',
									'payload_content_type': messages[i].payload.contentType || '',
									'payload_url': payloadUrl,
									'payload_duration': messages[i].payload.duration || '',
									'payload_size': messages[i].payload.size || '',
									'payload_width': messages[i].payload.width || '',
									'payload_height': messages[i].payload.height || '',
									'video_name': video.name || '',
									'video_content_type': video.contentType || '',
									'video_url': videoUrl,
									'video_duration': video.duration || '',
									'video_width': video.width || '',
									'video_height': video.height || '',
									'video_size': video.size || '',
									'thumbnail_content_type': thumbnail.contentType || '',
									'thumbnail_url': thumbnailUrl,
									'thumbnail_width': thumbnail.width || '',
									'thumbnail_height': thumbnail.height || '',
									'payload_video_url': messages[i].payload.videoUrl || '',
									'payload_thumbnai_url': messages[i].payload.thumbnailUrl || '',
									'payload_path': messages[i].payload.path || '',
								};
								let keys = Object.keys(insert)
								let keyStr = keys.toString()
								let valStr = ''
								for (let key in insert) {
									valStr += ('"' + insert[key] + '",')
								}
								valStr = valStr.substr(0, valStr.length - 1);
								let sqlStr = `INSERT INTO im_conversation_message(${keyStr}) values(${valStr})`

								insertData.push(sqlStr)

								if (messages[i].type === 'mergeTransmit') {

									let merge_data = []
									let merge_payload = payload
									console.log("merge_payload", merge_payload)
									for (let k = 0; k < merge_payload.length; k++) {

										let video = merge_payload[k].payload.video || {}
										let thumbnail = merge_payload[k].payload.thumbnail || {}
										let senderData = merge_payload[k].senderData || {}
										let payloadUrl = merge_payload[k].payload.url || ''
										let videoUrl = video.url || ''
										let thumbnailUrl = thumbnail.url || ''

										let merge_info = {
											'message_id': merge_payload[k].messageId,
											'merge_id': messageId,
											'receiver_id': groupId,
											'sender_id': merge_payload[k].senderId,
											'sender_name': senderData.name || '',
											'sender_avatar': senderData.avatar || '',
											'timestamp': merge_payload[k].timestamp,
											'message_type': merge_payload[k].type,
											'message_recalled': merge_payload[k].recalled ? 1 : 0,
											'message_status': merge_payload[k].status,
											'message_read': merge_payload[k].read ? 1 : 0,
											'payload_text': merge_payload[k].payload.text || '',
											'payload_name': merge_payload[k].payload.name || '',
											'payload_content_type': merge_payload[k].payload.contentType ||
												'',
											'payload_url': payloadUrl,
											'payload_duration': merge_payload[k].payload.duration || '',
											'payload_size': merge_payload[k].payload.size || '',
											'payload_width': merge_payload[k].payload.width || '',
											'payload_height': merge_payload[k].payload.height || '',
											'video_name': video.name || '',
											'video_content_type': video.contentType || '',
											'video_url': videoUrl,
											'video_duration': video.duration || '',
											'video_width': video.width || '',
											'video_height': video.height || '',
											'video_size': video.size || '',
											'thumbnail_content_type': thumbnail.contentType || '',
											'thumbnail_url': thumbnailUrl,
											'thumbnail_width': thumbnail.width || '',
											'thumbnail_height': thumbnail.height || '',
											'payload_video_url': merge_payload[k].payload.videoUrl || '',
											'payload_thumbnai_url': merge_payload[k].payload
												.thumbnailUrl || '',
											'payload_path': merge_payload[k].payload.path || '',
										};
										merge_data.push(merge_info)
									}

									//补充合并消息
									insert.merge_data = merge_data
								}
								messageData.push(insert)
							}

							that.lastMessageTimeStamp = messages[0].timestamp;
							that.insertSQLiteMessageData(insertData);
							that.messages = messageData.concat(that.messages);
							setTimeout(() => {
								that.viewIndex = "im_" + that.messages.length;
							}, 100)
							console.log("最新的消息哦", that.messages)
							that.scrollToBottom = scrollToBottom
							if (scrollToBottom) {
								that.scrollToBottom();
								//收到的消息设置为已读
								that.markPrivateMessageAsRead();
							}
						}
					},
					onFailed: (error) => {
						//获取失败
						console.log('获取历史消息失败:', error);
					}
				});
			},
			saveMergeMessage(groupId, mergeId, messages) {

				let insertData = []
				let messageData = []
				for (let i = 0; i < messages.length; i++) {

					let messageId = messages[i].messageId
					let video = messages[i].payload.video || {}
					let thumbnail = messages[i].payload.thumbnail || {}
					let senderData = messages[i].senderData || {}
					let payloadUrl = messages[i].payload.url || ''
					let videoUrl = video.url || ''
					let thumbnailUrl = thumbnail.url || ''

					//下载图片、视频、音频到本地
					this.downloadMessageFile(payloadUrl, messageId, 'payload_url', 'im_merge_message')
					this.downloadMessageFile(videoUrl, messageId, 'video_url', 'im_merge_message')
					this.downloadMessageFile(thumbnailUrl, messageId, 'thumbnail_url', 'im_merge_message')
					this.downloadMessageFile(senderData.avatar || '', messageId, 'sender_avatar', 'im_merge_message')
					this.downloadMessageFile(messages[i].payload.videoUrl || '', messageId, 'payload_video_url',
						'im_merge_message')
					this.downloadMessageFile(messages[i].payload.thumbnailUrl || '', messageId, 'payload_thumbnai_url',
						'im_merge_message')
					this.downloadMessageFile(messages[i].payload.path || '', messageId, 'payload_path', 'im_merge_message')


					//组装插入数据
					let insert = {
						'message_id': messages[i].messageId,
						'merge_id': mergeId,
						'receiver_id': groupId,
						'sender_id': messages[i].senderId,
						'sender_name': senderData.name || '',
						'sender_avatar': senderData.avatar || '',
						'timestamp': messages[i].timestamp,
						'message_type': messages[i].type,
						'message_recalled': messages[i].recalled ? 1 : 0,
						'message_status': messages[i].status,
						'message_read': messages[i].read ? 1 : 0,
						'payload_text': messages[i].payload.text || '',
						'payload_name': messages[i].payload.name || '',
						'payload_content_type': messages[i].payload.contentType || '',
						'payload_url': payloadUrl,
						'payload_duration': messages[i].payload.duration || '',
						'payload_size': messages[i].payload.size || '',
						'payload_width': messages[i].payload.width || '',
						'payload_height': messages[i].payload.height || '',
						'video_name': video.name || '',
						'video_content_type': video.contentType || '',
						'video_url': videoUrl,
						'video_duration': video.duration || '',
						'video_width': video.width || '',
						'video_height': video.height || '',
						'video_size': video.size || '',
						'thumbnail_content_type': thumbnail.contentType || '',
						'thumbnail_url': thumbnailUrl,
						'thumbnail_width': thumbnail.width || '',
						'thumbnail_height': thumbnail.height || '',
						'payload_video_url': messages[i].payload.videoUrl || '',
						'payload_thumbnai_url': messages[i].payload.thumbnailUrl || '',
						'payload_path': messages[i].payload.path || '',
					};
					let keys = Object.keys(insert)
					let keyStr = keys.toString()
					let valStr = ''
					for (let key in insert) {
						valStr += ('"' + insert[key] + '",')
					}
					valStr = valStr.substr(0, valStr.length - 1);
					let sqlStr = `INSERT INTO im_merge_message(${keyStr}) values(${valStr})`

					insertData.push(sqlStr)
				}

				this.insertSQLiteMessageData(insertData)
			},
			downloadMessageFile(url, messageId, key, table = 'im_conversation_message') {
				let that = this
				console.log("下载消息的图片", url)
				if (url != '' && url.indexOf('http') == 0) {
					console.log("进来了", url)
					uni.downloadFile({
						url: url,
						success: (res) => {
							if (res.statusCode === 200) {
								uni.saveFile({
									tempFilePath: res.tempFilePath,
									success: function(result) {

										console.log("下载好了", result.savedFilePath)
										//更新消息数据
										that.updateSQLiteMessageData(messageId, result
											.savedFilePath, key, table)
									},
								})
							}
						}
					})
				} else if (url != '') {
					console.log("进来了", url)
					uni.saveFile({
						tempFilePath: url,
						success: function(result) {

							//更新消息数据
							that.updateSQLiteMessageData(messageId, result.savedFilePath, key, table)
						},
					})
				}
			},
			//用于删除消息时更新本地存储数据
			deleteSQLiteMessageData(delData) {
				console.log('数据库删除语句', delData)
				let dbname = sqliteSQL.db.dbName
				let path = '_doc/' + this.vuex_user.uid + '.db'
				//打开数据库
				let isOpen = db.isOpenDB(dbname, path)
				if (isOpen) {
					plus.sqlite.executeSql({
						name: dbname,
						sql: delData,
						success: (e) => {
							console.log("历史消息删除成功", e);
						},
						fail: (e) => {
							console.log("历史消息删除失败", e);
						}
					})
				}
			},
			insertSQLiteMessageData(insertData) {

				let dbname = sqliteSQL.db.dbName
				let path = '_doc/' + this.vuex_user.uid + '.db'

				//打开数据库
				let isOpen = db.isOpenDB(dbname, path)
				if (isOpen) {
					plus.sqlite.executeSql({
						name: dbname,
						sql: insertData,
						success: (e) => {
							console.log("历史消息新增成功", e);
						},
						fail: (e) => {
							console.log("历史消息新增失败", e);
						}
					})
				}
			},
			updateSQLiteMessageData(messageId, url, key, table) {

				let dbname = sqliteSQL.db.dbName
				let path = '_doc/' + this.vuex_user.uid + '.db'
				let updateSql = `UPDATE ${table} SET ${key} = "${url}" WHERE message_id = "${messageId}";`


				console.log("updateSql", updateSql)

				//打开数据库
				let isOpen = db.isOpenDB(dbname, path)
				if (isOpen) {
					plus.sqlite.executeSql({
						name: dbname,
						sql: updateSql,
						success: (e) => {
							console.log("消息图片更新成功", e);
						},
						fail: (e) => {
							console.log("消息图片更新失败", e);
						}
					})
				}
			},
			showAllData(message) {
				let that = this;
				var params = {
					messages: JSON.stringify(message.merge_data)
				}
				that.$u.route({
					url: `/pages/note/mergetransmit/index`,
					params
				})
			},
			getmess(msg) {
				this.msgarr2 = msg.merge_data || []
			},
			connectGoEasy() {
				console.log("this.vuex_user.avatar", this.vuex_user.avatar);
				this.goEasy.connect({
					id: this.vuex_user.uid,
					data: {
						name: this.vuex_user.uname,
						avatar: this.vuex_user.avatar
					},
					onSuccess: () => {
						console.log('GoEasy connect successfully.')
					},
					onFailed: (error) => {
						console.log('Failed to connect GoEasy, code:' + error.code + ',error:' + error
							.content);
					},
					onProgress: (attempts) => {
						console.log('GoEasy is connecting', attempts);
					}
				});

				//订阅Goeasy消息
				this.goEasy.pubsub.subscribe({
					channel: "user" + this.vuex_user.uid,
					onMessage: function(message) {
						console.log("Channel:" + message.channel + " content:" +
							message.content);
					},
					onSuccess: function() {
						console.log("Channel订阅成功。");
					},
					onFailed: function(error) {
						console.log("Channel订阅失败, 错误编码：" + error.code + " 错误信息：" +
							error.content)
					}
				});
			},
			//渲染文本消息，如果包含表情，替换为图片
			//todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
			renderTextMessage(message) {
				// console.log( this.emoji.decoder.decode(message.payload.text))
				return '<span class="text-content">' + this.emoji.decoder.decode(message.payload_text) + '</span>';
			},
			transmitRenderTextMessage(message) {
				// console.log("---合并转发消息----"+JSON.stringify(message));
				return '<span class="transmit-box-content-text">' + '--:' + this.emoji.decoder.decode(message
					.payload_text) + '</span>'
			},
			//像微信那样显示时间，如果有几分钟没发消息了，才显示时间
			//todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
			renderMessageDate(message, index) {
				// console.log("------gruoprenderMessageDatemessage--------"+message.timestamp);
				if (index === 0) {
					return this.formatDate(message.timestamp);
				} else {
					if (message.timestamp - this.messages[index - 1].timestamp > 5 * 60 * 1000) {
						return this.formatDate(message.timestamp);
					}
				}
				return '';
			},
			sendMessageNickname(message) {
				if (this.groupMemberDict[message.sender_id]) {
					return this.groupMemberDict[message.sender_id].UserName
				}

				return message.sender_name
			},
			initialGoEasyListeners() {
				//监听群聊消息
				this.goEasy.im.on(this.GoEasy.IM_EVENT.GROUP_MESSAGE_RECEIVED, (message) => {
					let groupId = message.groupId;
					if (groupId == this.groupId) {

						let that = this
						let messageId = message.messageId
						let senderData = message.senderData || {}
						let video = message.payload.video || {}
						let thumbnail = message.payload.thumbnail || {}
						let payloadUrl = message.payload.url || ''
						let videoUrl = video.url || ''
						let thumbnailUrl = thumbnail.url || ''
						let insertData = []
						let fileUrl = message.buildOptions.createOptions.file.path
						let data = {
							'message_id': message.messageId,
							'receiver_id': message.groupId || '',
							'sender_id': message.senderId,
							'sender_name': senderData.name || '',
							'sender_avatar': senderData.avatar || '',
							'timestamp': message.timestamp,
							'message_type': message.type,
							'message_recalled': message.recalled ? 1 : 0,
							'message_status': message.status,
							'message_read': message.read ? 1 : 0,
							'payload_text': message.payload.text || '',
							'payload_name': message.payload.name || '',
							'payload_content_type': message.payload.contentType || '',
							'payload_url': payloadUrl,
							'payload_duration': message.payload.duration || '',
							'payload_size': message.payload.size || '',
							'payload_width': message.payload.width || '',
							'payload_height': message.payload.height || '',
							'video_name': video.name || '',
							'video_content_type': video.contentType || '',
							'video_url': videoUrl,
							'video_duration': video.duration || '',
							'video_width': video.width || '',
							'video_height': video.height || '',
							'video_size': video.size || '',
							'thumbnail_content_type': thumbnail.contentType || '',
							'thumbnail_url': thumbnailUrl,
							'thumbnail_width': thumbnail.width || '',
							'thumbnail_height': thumbnail.height || '',
							'payload_video_url': message.payload.videoUrl || '',
							'payload_thumbnai_url': message.payload.thumbnailUrl || '',
							'payload_path': message.payload.path || '',
						};
						let keys = Object.keys(data)
						let keyStr = keys.toString()
						let valStr = ''
						for (let key in data) {
							valStr += ('"' + data[key] + '",')
						}
						valStr = valStr.substr(0, valStr.length - 1);
						let sqlStr = `INSERT INTO im_conversation_message(${keyStr}) values(${valStr})`
						insertData.push(sqlStr)


						this.insertSQLiteMessageData(insertData)
						let thumbnail2 = message.payload.thumbnail || {}
						console.log("缩略图缩略", thumbnail2.url)

						data.thumbnail_url = thumbnail2.url
						this.messages.push(data);

						//下载图片、视频、音频到本地
						this.downloadMessageFile(payloadUrl, messageId, 'payload_url')
						this.downloadMessageFile(videoUrl, messageId, 'video_url')
						this.downloadMessageFile(message.payload.thumbnail.url || '', messageId, 'thumbnail_url')
						this.downloadMessageFile(senderData.avatar || '', messageId, 'sender_avatar')

						//聊天时，收到消息标记为已读
						this.markGroupMessageAsRead(groupId);
						//收到新消息，是滚动到最底部
						this.scrollToBottom();
					}
				});
				//监听消息删除
				this.goEasy.im.on(this.GoEasy.IM_EVENT.MESSAGE_DELETED, (deletedMessages) => {
					deletedMessages.forEach(message => {
						let groupId = message.groupId;
						if (groupId && groupId == this.groupId) {
							let index = this.messages.indexOf(message);
							if (index > -1) {
								this.messages.splice(index, 1);
							}
						}
					});
				})
			},
			initRecorderListeners() {
				// 监听录音开始
				recorderManager.onStart(() => {
					this.audio.recording = true;
					this.audio.startTime = Date.now();
				});
				//录音结束后，发送
				recorderManager.onStop((res) => {
					let endTime = Date.now();
					this.audio.recording = false;
					let duration = endTime - this.audio.startTime;
					if (duration < 1000) {
						uni.showToast({
							icon: 'error',
							title: this.$t('chat.chat_recording_time'),
							duration: 500
						});
						return;
					}
					if (this.RecordCancel == 1) {
						return;
					}
					res.duration = duration;
					let audioMessage = this.goEasy.im.createAudioMessage({
						to: {
							id: this.groupId,
							type: this.GoEasy.IM_SCENE.GROUP,
							data: {
								name: this.group.GroupName,
								avatar: this.group.GroupAvatarImg != '' ? this.group.GroupAvatarImg :
									'/static/static/assets/gruopavatar.svg'
							}
						},
						file: res,
						onProgress: function(progress) {
							console.log(progress);
						},
						notification: {
							title: this.currentUser.uname + this.$t('chat.chat_send_voice'),
							body: '[' + this.$t('chat.chat_voice_message') + ']' // 字段最长 50 字符
						}
					});
					this.sendMessage(audioMessage);
				});
				// 监听录音报错
				recorderManager.onError((res) => {
					this.audio.recording = false;
					recorderManager.stop();
					uni.showToast({
						icon: 'none',
						title: this.$t('chat.chat_recording_error'),
						duration: 1000
					});
				})
			},
			sendMessage(message) {

				let that = this
				let messageId = message.messageId
				let senderData = message.senderData || {}
				let video = message.payload.video || {}
				let thumbnail = message.payload.thumbnail || {}
				let payloadUrl = message.payload.url || ''
				let videoUrl = video.url || ''
				let thumbnailUrl = thumbnail.url || ''
				let insertData = []

				let data = {
					'message_id': message.messageId,
					'receiver_id': message.groupId || '',
					'sender_id': message.senderId,
					'sender_name': senderData.name || '',
					'sender_avatar': senderData.avatar || '',
					'timestamp': message.timestamp,
					'message_type': message.type,
					'message_recalled': message.recalled ? 1 : 0,
					'message_status': message.status,
					'message_read': message.read ? 1 : 0,
					'payload_text': message.payload.text || '',
					'payload_name': message.payload.name || '',
					'payload_content_type': message.payload.contentType || '',
					'payload_url': payloadUrl,
					'payload_duration': message.payload.duration || '',
					'payload_size': message.payload.size || '',
					'payload_width': message.payload.width || '',
					'payload_height': message.payload.height || '',
					'video_name': video.name || '',
					'video_content_type': video.contentType || '',
					'video_url': videoUrl,
					'video_duration': video.duration || '',
					'video_width': video.width || '',
					'video_height': video.height || '',
					'video_size': video.size || '',
					'thumbnail_content_type': thumbnail.contentType || '',
					'thumbnail_url': thumbnailUrl,
					'thumbnail_width': thumbnail.width || '',
					'thumbnail_height': thumbnail.height || '',
					'payload_video_url': message.payload.videoUrl || '',
					'payload_thumbnai_url': message.payload.thumbnailUrl || '',
					'payload_path': message.payload.path || '',
				};
				let keys = Object.keys(data)
				let keyStr = keys.toString()
				let valStr = ''
				for (let key in data) {
					valStr += ('"' + data[key] + '",')
				}
				valStr = valStr.substr(0, valStr.length - 1);
				let sqlStr = `INSERT INTO im_conversation_message(${keyStr}) values(${valStr})`
				insertData.push(sqlStr)

				this.goeasyMessages.push(message)
				this.scrollToBottom = true
				this.goEasy.im.sendMessage({
					message: message,
					onSuccess: (message) => {
						console.log('发送成功.', message);
						that.insertSQLiteMessageData(insertData)
						let thumbnail = message.payload.thumbnail || {}
						console.log("缩略图缩略", thumbnail.url)

						data.thumbnail_url = thumbnail.url
						that.messages.push(data);

						that.viewIndex = "";
						//设置viewIndex值，使聊天滚动到底部
						console.log('viewIndex', "im_" + that.messages.length)
						that.$nextTick(() => {
							that.viewIndex = "im_" + that.messages.length;
						})

						//下载图片、视频、音频到本地
						that.downloadMessageFile(payloadUrl, messageId, 'payload_url')
						that.downloadMessageFile(videoUrl, messageId, 'video_url')
						that.downloadMessageFile(message.payload.thumbnail.url || '', messageId,
							'thumbnail_url')
						that.downloadMessageFile(senderData.avatar || '', messageId, 'sender_avatar')

						that.otherTypesMessagePanelVisible = false
						that.emoji.visible = false
					},
					onFailed: function(error) {
						if (error.code === 507) {
							console.log(
								'发送语音/图片/视频/文件失败，没有配置OSS存储，详情参考：https://www.goeasy.io/cn/docs/goeasy-2.x/im/message/media/send-media-message.html'
							);
						} else {
							uni.showToast({
								title: error,
								icon: 'none',
							});
						}
					}
				});

			},
			createTextMessage() {
				if (this.content.trim() !== '') {
					let body = this.content;
					if (this.content.length >= 50) {
						body = this.content.substring(0, 30) + '...';
					}
					console.log(this.content)
					let textMessage = this.goEasy.im.createTextMessage({
						text: this.content,
						to: {
							id: this.groupId,
							type: this.GoEasy.IM_SCENE.GROUP,
							data: {
								name: this.group.GroupName,
								avatar: this.group.GroupAvatarImg != '' ? this.group.GroupAvatarImg :
									'/static/static/assets/gruopavatar.svg'
							}
						},
						notification: {
							title: this.currentUser.uname + this.$t('chat.chat_send_text'),
							body: body // 字段最长 50 字符
						}
					});
					this.sendMessage(textMessage);

				}
				this.content = '';
				this.emoji.visible = false
				this.changeSendMode = 'add'
			},
			createVideoMessage() {
				uni.chooseVideo({
					success: (res) => {
						let videoMessage = this.goEasy.im.createVideoMessage({
							to: {
								id: this.groupId,
								type: this.GoEasy.IM_SCENE.GROUP,
								data: {
									name: this.group.GroupName,
									avatar: this.group.GroupAvatarImg != '' ? this.group
										.GroupAvatarImg : '/static/static/assets/gruopavatar.svg'
								}
							},
							file: res,
							onProgress: function(progress) {
								console.log(progress)
							},
							notification: {
								title: this.currentUser.uname + this.$t('chat.chat_send_video'),
								body: '[' + this.$t('chat.chat_video_message') + ']' // 字段最长 50 字符
							}
						});
						this.sendMessage(videoMessage);
					}
				})
			},
			createImageMessage() {
				uni.chooseImage({
					count: 9,
					success: (res) => {
						res.tempFiles.forEach(file => {
							let imageMessage = this.goEasy.im.createImageMessage({
								to: {
									id: this.groupId,
									type: this.GoEasy.IM_SCENE.GROUP,
									data: {
										name: this.group.GroupName,
										avatar: this.group.GroupAvatarImg != '' ? this.group
											.GroupAvatarImg :
											'/static/static/assets/gruopavatar.svg'
									}
								},
								file: file,
								onProgress: function(progress) {
									console.log(progress)
								},
								notification: {
									title: this.currentUser.uname + this.$t('chat')
										.chat_send_message,
									body: '[' + this.$t('chat.chat_image_message') +
										']' // 字段最长 50 字符
								}
							});
							this.sendMessage(imageMessage);
						})
					}
				});
			},
			appendMessage(e) {
				if(this.content !== undefined){
					this.content = this.content.slice(0,this.cursorStart) + e.detail.message +this.content.slice(this.cursorStart);
				}else{
					this.content = e.detail.message
				}
				this.changeSendMode = 'send'
			},
			deleteEmojiMessage() {
				if (this.content.charAt(this.content.length - 1) == ']') {
					let index = this.content.lastIndexOf('[')
					this.content = this.content.substring(0, index)
					if (this.content == '') {
						this.changeSendMode = 'add'
					}
				}
			},
			scrollView(e) {
				this.scrollTop = e.target.scrollTop
			},
			longPress(message, index) {
				this.isShowTip = false
				this.timeOut = setTimeout(() => {
					this.isShowTip = true
				}, 300)

				this.currentMessage = message
				console.log(message)
				console.log(this.currentMessage.type)
				if (message.sender_id == this.currentUser.uid) {
					this.isMine = true
				} else {
					this.isMine = false
				}
				console.log(" 打开 点击了")
				const MAX_RECALLABLE_TIME = 1440 * 60 * 1000; //1天以内的消息才可以撤回

				console.log("index", index)

				let goeasyMessage = {}
				for (let i = 0; i < this.goeasyMessages.length; i++) {
					if (this.goeasyMessages[i].messageId === message.message_id) {
						goeasyMessage = this.goeasyMessages[i]
						break
					}
				}

				this.messageSelector.messages = [goeasyMessage];
				if ((Date.now() - message.timestamp) < MAX_RECALLABLE_TIME && message.sender_id == this.currentUser
					.uid &&
					(message.message_status === 'success' || message.message_status === 'new')) {
					this.actionPopup.recallable = true;
				} else {
					this.actionPopup.recallable = false;
				}
				this.actionPopup.index = index;
				var query = uni.createSelectorQuery();
				query.select('#content' + message.message_id).boundingClientRect(res => {
					console.log(res)
					this.top = this.scrollTop + res.top - 130

					if (message.message_type != 'text') {
						this.top = this.scrollTop + res.top - 80
					}
					this.clientY = res.top
					console.log(this.clientY)
					if (this.clientY < 0) {
						this.top = this.top - res.top + 200
					}
					// if (this.ifLongtap) {
					// 	// 长按后触发的事件
					// 	this.showActionPopup(message, index);
					// }
				}).exec()
			},
			touchEnd() {
				this.ifLongtap = true;
			},
			touchMove(e) {
				// 手指触摸后的移动事件
				this.ifLongtap = false;
				clearTimeout(this.timeOut); //清除定时器
				this.timeOut = 0; 
			},
			showActionPopup(message, index) {
				console.log(" 打开 点击了")
				const MAX_RECALLABLE_TIME = 1440 * 60 * 1000; //1天以内的消息才可以撤回

				console.log("index", index)

				let goeasyMessage = {}
				for (let i = 0; i < this.goeasyMessages.length; i++) {
					if (this.goeasyMessages[i].messageId === message.message_id) {
						goeasyMessage = this.goeasyMessages[i]
						break
					}
				}

				console.log("goeasyMessage", goeasyMessage)
				this.messageSelector.messages = [goeasyMessage];
				if ((Date.now() - message.timestamp) < MAX_RECALLABLE_TIME && message.sender_id == this.currentUser
					.uid &&
					(message.message_status === 'success' || message.message_status === 'new')) {
					this.actionPopup.recallable = true;
				} else {
					this.actionPopup.recallable = false;
				}
				this.actionPopup.visible = true;
				this.actionPopup.index = index;
			},
			deleteSingleMessage() {
				if (JSON.stringify(this.messageSelector.messages[0]) === '{}') {
					//判断messageSelector.messages是否有数据
					uni.showToast({
						title: this.$t('chat.no_message'),
						icon: 'none'
					})
					this.isShowTip = false
				} else {
					uni.showModal({
						content: this.$t('chat.chat_confirm_delete'),
						cancelText: this.$t('chat.btn_confirm'),
						confirmText: this.$t('chat.btn_cancel'),
						success: (res) => {
							this.actionPopup.visible = false;
							if (!res.confirm) {
								this.deleteMessage();
							}
						},
					})
				}
			},
			deleteMultipleMessages() {
				if (this.messageSelector.messages.length > 0) {
					uni.showModal({
						content: this.$t('chat.chat_confirm_delete'),
						cancelText: this.$t('chat.btn_confirm'),
						confirmText: this.$t('chat.btn_cancel'),
						success: (res) => {
							this.messageSelector.visible = false;
							if (!res.confirm) {
								this.deleteMessage();
							}
						},
					})
				}
			},
			deleteMessage() {
				let goeasyMessage = []
				console.log(this.goeasyMessages)
				this.messageSelector.messages.forEach(message => {
					for (let i = 0; i < this.goeasyMessages.length; i++) {
						//判断是单条删除还是多条删除
						if (message.hasOwnProperty('messageId')) {
							//单条删除
							if (this.goeasyMessages[i].messageId === message.messageId) {
								goeasyMessage.push(this.goeasyMessages[i])
							}

						} else {
							//多条删除
							if (this.goeasyMessages[i].messageId === message.message_id) {
								goeasyMessage.push(this.goeasyMessages[i])
							}
						}
					}
				})
				console.log(goeasyMessage)
				this.goEasy.im.deleteMessage({
					messages: goeasyMessage,
					onSuccess: (result) => {
						console.log('删除成功')
						let messageTemp = this.messages
						let delsql = []
						console.log(messageTemp)
						//将消息列表与选中消息作对比，并在前端也将该消息删除并更新视图
						goeasyMessage.forEach(message => {
							messageTemp.forEach((item, index) => {
								if (item.message_id == message.messageId) {
									console.log('进来几次删除删除删除元素元素元素')
									this.messages.splice(index, 1);
									//执行数据库删除语句
									let sqlStr =
										`DELETE FROM im_conversation_message WHERE message_id='${item.message_id}'`
									delsql.push(sqlStr)
								}
							})
						});
						//相应地将本地存储中某条数据也删除
						this.deleteSQLiteMessageData(delsql)
						this.isShowTip = false
						this.messageSelector.messages = [];
					},
					onFailed: (error) => {
						console.log('error:', error);
					}

				})
			},
			recallMessage() {
				console.log("this.messageSelector.messages", this.messageSelector.messages)
				this.actionPopup.visible = false;
				this.isShowTip = false
				this.goEasy.im.recallMessage({
					messages: this.messageSelector.messages,
					onSuccess: () => {
						console.log("this.actionPopup.index", this.actionPopup.index)
						if (this.actionPopup.index !== null && this.messages[this.actionPopup.index]) {
							this.messages[this.actionPopup.index].message_recalled = 1
							this.updateSQLiteMessage(this.messages[this.actionPopup.index].message_id, 1)
						}
						uni.showToast({
							title: that.$t('chat.chat_recall_success'),
							icon: 'none',
						});
						this.isShowTip = false
					},
					onFailed: (error) => {
						console.log('撤回失败,error:', error);
					}
				});
			},
			copyMessage() {
				let that = this;
				that.actionPopup.visible = false;
				uni.setClipboardData({
					data: that.currentMessage.payload_text || '',
					showToast: false,
					success: function() {
						uni.showToast({
							title: that.$t('chat.chat_copy_success'),
							icon: 'none',
						});
					},
				});
			},
			transmitMultipleMessages() {
				var that = this;
				if (that.messageSelector.messages.length > 0) {
					uni.showActionSheet({
						itemList: [this.$t('chat.every_forward'), this.$t('chat.merge_forward')],
						success: function(res) {
							that.messageSelector.visible = false;
							// console.log('我选中了第' + (res.tapIndex + 1) + '个按钮');
							if (res.tapIndex == 1) {
								var nowsend = 0
								that.messageSelector.messages.forEach(function(value, index) {
									if (value.type === "mergeTransmit" || value.type === "audio") {
										//that.messageSelector.messages.splice(index, 1);
										nowsend = 1;
										//break;
									}
								});
								if (nowsend == 0) {
									that.transmitMessageToAll(that.messageSelector.messages, 2);
								} else if (nowsend == 1) {
									nowsend = 0
									// uni.showModal({
									// 	content: "选择消息中，聊天记录暂不支持合并转发，转发后不显示内容.",
									// 	confirmText: "继续发送",
									// 	cancelText:"取消",
									// 	success: (res) => {
									// 		if (res.confirm) {
									// 			if (that.messageSelector.messages.length>0){
									// 				that.transmitMessageToAll(that.messageSelector.messages,2);
									// 			}
									// 		}else if(res.cancel){
									// 			that.messageSelector.visible = false;
									// 		}
									// 	},
									// })
									plus.nativeUI.confirm("选择消息中，聊天记录暂不支持合并转发，转发后不显示内容.", function(e) {
										console.log("Close confirm: " + e.index);
										if (e.index == 0) {
											that.messageSelector.messages.forEach(function(value1,
												index1) {
												if (value1.type === "mergeTransmit" || value1
													.type === "audio") {
													that.messageSelector.messages.splice(
														index1, 1);
												}
											});
											if (that.messageSelector.messages.length > 0) {
												that.transmitMessageToAll(that.messageSelector
													.messages, 2);
											}
										} else if (e.index == 1) {
											that.messageSelector.visible = true;
										}
									}, "", ["继续发送", "取消"]);
								}
							} else {
								that.transmitMessageToAll(that.messageSelector.messages, 1);
							}
							// that.transmitMessageToAll(that.messageSelector.messages,res.tapIndex+1);
						},
						fail: function(res) {
							console.log(res.errMsg);
						}
					});
				}
			},
			TranslateNew() {
				var _this = this;
				//获取token
				uni.request({
					url: 'https://aip.baidubce.com/oauth/2.0/token', //仅为示例，并非真实接口地址。
					data: {
						grant_type: 'client_credentials',
						client_id: 'i8gWcp897FTGlpghRPunGgqq',
						client_secret: 'hYCRb6UGhgdBC1phXk52kXWwpdvmsy8P',
					},
					header: {
						'Content-Type': 'application/json;charset=utf-8' //自定义请求头信息
					},
					success: (res) => {
						//console.log("---token---"+res.data.access_token);
						// console.log(JSON.stringify(res) + "-token--识别结果");
						_this.token = res.data.access_token;
						// alert( _this.resContent)

						//_this.PostData(ids);
						// _this.$refs.popup.open()
					}
				});
			},

			Translate(ids) {
				var that = this
				var fromLang = ''
				var toLang = ''
				switch (ids) {
					case 1:
						fromLang = 'en'
						toLang = 'zh'
						break;
					case 2:
						fromLang = 'ru'
						toLang = 'zh'
						break;
					case 3:
						fromLang = 'zh'
						toLang = 'en'
						break;
					case 4:
						fromLang = 'zh'
						toLang = 'ru'
						break;
					default:
						break;
				}
				console.log(that.messageSelector.messages[0])
				var postData = {
          q: that.messageSelector.messages[0].payload.text, //翻译内容
					from: fromLang,
					to: toLang, //中文
				}
				//调用百度机器翻译接口
				uni.request({
					url: 'https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=' + that
						.token, //仅为示例，并非真实接口地址。
					data: postData,
					header: {
						'Content-Type': 'application/json;charset=utf-8' //'Content-Type':'audio/pcm;rate=16000' //自定义请求头信息
					},
					method: 'POST',
					success: (res) => {
            var mgs = that.messageSelector.messages[0].messageId
						// that.dicttext[mgs] = res.data.result.trans_result[0].dst
						// that.dicttext[mgs] = "";
						var valarr = res.data.result.trans_result
						if (valarr.length > 0) {
							for (var i = 0; i < valarr.length; i++) {
								if (i == 0) {
									that.dicttext[mgs] = valarr[i].dst + "\r\n"
								} else {
									that.dicttext[mgs] += valarr[i].dst + "\r\n"
								}
							}
						}
						//console.log(that.dicttext[mgs]+ "----翻译识别结果");
						that.isShowTip = false
						//this.resContent = res.data.result.trans_result[0].dst;
						//that.messageSelector.messages[0].payload.text =  that.messageSelector.messages[0].payload.text + res.data.result.trans_result[0].dst
						// that.dataTranslate=res.data.result.trans_result[0].dst;
						//console.log(that.messageSelector.messages[0].payload.text + "----翻译结果");
						//console.log(JSON.stringify(that.messageSelector.messages[0]) + "翻译识别结果");
					}
				})
			},

			transmitMessageToAll(nowmessages, nowtype) {
				// console.log("===多选数据："+JSON.stringify(nowmessages));
				let that = this;
				// console.log("-----------transmitMessage---------------"+JSON.stringify(that.messageSelector.messages[0]));

				//that.actionPopup.visible = false;
				var params = {
					title: "选择好友或群",
					messages: JSON.stringify(nowmessages),
					type: nowtype
				};
				//var params = {title:"选择好友或群",messages:nowmessages,type:nowtype};
				that.$u.route({
					url: `/pages/note/transmit/index`,
					params
				})
			},
			transmitMessage() {

				// console.log("-----------transmitMessageGroup---------------");
				let that = this;
				that.actionPopup.visible = false;
				var params = {
					title: "选择好友或群",
					messages: JSON.stringify(that.messageSelector.messages[0]),
					type: 0
				};
				this.isShowTip = false
				that.$u.route({
					url: `/pages/note/transmit/index`,
					params
				})
			},
			editRecalledMessage(content) {
				if (this.audio.visible) {
					this.audio.visible = false;
				}
				this.content = content;
			},
			showCheckBox() {
				this.messageSelector.messages = [];
				this.messageSelector.visible = true;
				this.actionPopup.visible = false;
			},
			selectMessages(e) {
				const selectedMessageIds = e.detail.value;
				let selectedMessages = [];
				this.messages.forEach(message => {
					if (selectedMessageIds.includes(message.message_id)) {
						selectedMessages.push(message);
					}
				})
				this.messageSelector.messages = selectedMessages;
			},
			loadHistoryMessage(scrollToBottom) { //历史消息
				let that = this
				let lastMessageTimeStamp;
				let lastMessage = this.goeasyMessages[0];
				if (lastMessage) {
					lastMessageTimeStamp = lastMessage.timestamp;
				}
				this.goEasy.im.history({
					groupId: this.groupId,
					lastTimestamp: lastMessageTimeStamp,
					limit: 10,
					onSuccess: (result) => {
						let messages = result.content;
						if (messages.length > 0) {

							console.log("最后时间1", that.lastMessageTime)
							console.log("最后时间2", messages[messages.length - 1].timestamp)

							// if (that.lastMessageTime > messages[messages.length - 1].timestamp) {
							console.log("更新的 messages", messages)

							let insertData = []
							let messageData = []
							for (let i = 0; i < messages.length; i++) {

								let messageId = messages[i].messageId
								let video = messages[i].payload.video || {}
								let thumbnail = messages[i].payload.thumbnail || {}
								let senderData = messages[i].senderData || {}
								let payloadUrl = messages[i].payload.url || ''
								let videoUrl = video.url || ''
								let thumbnailUrl = thumbnail.url || ''
								let payload = messages[i].payload || {}
								if (messages[i].type === 'mergeTransmit') {

									//补充合并消息
									payload = JSON.parse(payload)
									this.saveMergeMessage(this.groupId, messageId, payload)
								}

								//下载图片、视频、音频到本地
								this.downloadMessageFile(payloadUrl, messageId, 'payload_url')
								this.downloadMessageFile(videoUrl, messageId, 'video_url')
								this.downloadMessageFile(thumbnailUrl, messageId, 'thumbnail_url')
								this.downloadMessageFile(senderData.avatar || '', messageId,
									'sender_avatar')
								this.downloadMessageFile(messages[i].payload.videoUrl || '', messageId,
									'payload_video_url')
								this.downloadMessageFile(messages[i].payload.thumbnailUrl || '', messageId,
									'payload_thumbnai_url')
								this.downloadMessageFile(messages[i].payload.path || '', messageId,
									'payload_path')

								//组装插入数据
								let insert = {
									'message_id': messages[i].messageId,
									'receiver_id': this.groupId,
									'sender_id': messages[i].senderId,
									'sender_name': senderData.name || '',
									'sender_avatar': senderData.avatar || '',
									'timestamp': messages[i].timestamp,
									'message_type': messages[i].type,
									'message_recalled': messages[i].recalled ? 1 : 0,
									'message_status': messages[i].status,
									'message_read': messages[i].read ? 1 : 0,
									'payload_text': messages[i].payload.text || '',
									'payload_name': messages[i].payload.name || '',
									'payload_content_type': messages[i].payload.contentType || '',
									'payload_url': payloadUrl,
									'payload_duration': messages[i].payload.duration || '',
									'payload_size': messages[i].payload.size || '',
									'payload_width': messages[i].payload.width || '',
									'payload_height': messages[i].payload.height || '',
									'video_name': video.name || '',
									'video_content_type': video.contentType || '',
									'video_url': videoUrl,
									'video_duration': video.duration || '',
									'video_width': video.width || '',
									'video_height': video.height || '',
									'video_size': video.size || '',
									'thumbnail_content_type': thumbnail.contentType || '',
									'thumbnail_url': thumbnailUrl,
									'thumbnail_width': thumbnail.width || '',
									'thumbnail_height': thumbnail.height || '',
									'payload_video_url': messages[i].payload.videoUrl || '',
									'payload_thumbnai_url': messages[i].payload.thumbnailUrl || '',
									'payload_path': messages[i].payload.path || '',
								};
								let keys = Object.keys(insert)
								let keyStr = keys.toString()
								let valStr = ''
								for (let key in insert) {
									valStr += ('"' + insert[key] + '",')
								}
								valStr = valStr.substr(0, valStr.length - 1);
								let sqlStr =
									`REPLACE INTO im_conversation_message(${keyStr}) values(${valStr})`

								insertData.push(sqlStr)
							}

							that.goeasyMessages = messages.concat(that.goeasyMessages);
							that.insertSQLiteMessageData(insertData)
							that.markGroupMessageAsRead(that.groupId)
							// }
						}
					},
					onFailed: (error) => {
						//获取失败
						console.log('获取历史消息失败:', error);
					}
				});
			},

			updateSQLiteMessage(messageId, recalled) {

				let dbname = sqliteSQL.db.dbName
				let path = '_doc/' + this.vuex_user.uid + '.db'
				let updateSql =
					`UPDATE im_conversation_message SET message_recalled=${recalled} WHERE message_id = "${messageId}";`

				//打开数据库
				let isOpen = db.isOpenDB(dbname, path)
				if (isOpen) {
					plus.sqlite.executeSql({
						name: dbname,
						sql: updateSql,
						success: (e) => {
							console.log("消息状态更新成功", e);
						},
						fail: (e) => {
							console.log("消息状态更新失败", e);
						}
					})
				}
			},
			getServerMessageList(stat) {
				if (this.allHistoryLoaded) {
					uni.stopPullDownRefresh();
					return;
				}
				let that = this;
				let lastMessageTimeStamp = this.lastMessageTimeStamp;
				let query = {
					idx: that.idx,
					size: 10,
					conversation_id: 'GROUP' + this.groupId,
					conversation_type: 'GROUP',
					last_message_time: lastMessageTimeStamp === null ? 0 : lastMessageTimeStamp / 1000
				};
				console.log("query", query)
				that.$http.get('/mgr/user/chat/history/message/data', query).then(res => {
					uni.stopPullDownRefresh();
					if (res === null || res.length == 0) {
						that.allHistoryLoaded = true;
						return
					}

					console.log("获取服务消息了", res);
					let messages = res;
					that.idx = that.idx + 1;

					let insertData = []
					let messageData = []
					for (let i = 0; i < messages.length; i++) {

						let messageId = messages[i].messageId
						let video = messages[i].payload.video || {}
						let thumbnail = messages[i].payload.thumbnail || {}
						let senderData = messages[i].senderData || {}
						let payloadUrl = messages[i].payload.url || ''
						let videoUrl = video.url || ''
						let thumbnailUrl = thumbnail.url || ''

						//下载图片、视频、音频到本地
						this.downloadMessageFile(payloadUrl, messageId, 'payload_url')
						this.downloadMessageFile(videoUrl, messageId, 'video_url')
						this.downloadMessageFile(thumbnailUrl, messageId, 'thumbnail_url')
						this.downloadMessageFile(senderData.avatar || '', messageId, 'sender_avatar')

						//组装插入数据
						let insert = {
							'message_id': messages[i].messageId,
							'receiver_id': messages[i].groupId || '',
							'sender_id': messages[i].senderId,
							'sender_name': senderData.name || '',
							'sender_avatar': senderData.avatar || '',
							'timestamp': messages[i].timestamp,
							'message_type': messages[i].type,
							'message_recalled': messages[i].recalled ? 1 : 0,
							'message_status': messages[i].status,
							'message_read': messages[i].read ? 1 : 0,
							'payload_text': messages[i].payload.text || '',
							'payload_name': messages[i].payload.name || '',
							'payload_content_type': messages[i].payload.contentType || '',
							'payload_url': payloadUrl,
							'payload_duration': messages[i].payload.duration || '',
							'payload_size': messages[i].payload.size || '',
							'payload_width': messages[i].payload.width || '',
							'payload_height': messages[i].payload.height || '',
							'video_name': video.name || '',
							'video_content_type': video.contentType || '',
							'video_url': videoUrl,
							'video_duration': video.duration || '',
							'video_width': video.width || '',
							'video_height': video.height || '',
							'video_size': video.size || '',
							'thumbnail_content_type': thumbnail.contentType || '',
							'thumbnail_url': thumbnailUrl,
							'thumbnail_width': thumbnail.width || '',
							'thumbnail_height': thumbnail.height || '',
							'payload_video_url': messages[i].payload.videoUrl || '',
							'payload_thumbnai_url': messages[i].payload.thumbnailUrl || '',
							'payload_path': messages[i].payload.path || '',
						};
						let keys = Object.keys(insert)
						let keyStr = keys.toString()
						let valStr = ''
						for (let key in insert) {
							valStr += ('"' + insert[key] + '",')
						}
						valStr = valStr.substr(0, valStr.length - 1);
						let sqlStr = `INSERT INTO im_conversation_message(${keyStr}) values(${valStr})`

						insertData.push(sqlStr)
						messageData.push(insert)
					}

					that.lastMessageTimeStamp = messages[messages.length - 1].timestamp
					that.insertSQLiteMessageData(insertData)
					that.messages = [...messageData, ...that.messages];
					setTimeout(() => {
						that.viewIndex = "im_" + that.messages.length;
					}, 100)
					//console.log("合并最后看到的消息了", that.messages)

					//检查数据是否已拉取完
					if (messages.length == 0) {
						that.allHistoryLoaded = true;
					}
				});
			},
			showMembers() { //显示群成员
				uni.navigateTo({
					url: '../groupChat/member?users=' + JSON.stringify(this.groupMembers)
				});
			},
			onRecordStart(e) {
				this.RecordCancel = 0;
				this.startX = 0;
				this.startY = 0;
				this.endX = 0;
				this.endY = 0;
				var touch = e.touches[0]
				this.startX = touch.pageX;
				this.startY = touch.pageY
				console.log("startX:" + this.startX + "," + "startY:" + this.startY);
				try {
					var options = {};
					options.format = "pcm"
					options.sampleRate = 16000
					options.numberOfChannels = 1
					options.audioSource = "auto"
					options.encodeBitRate = 48000
					recorderManager.start(options);
					// recorderManager.start();
				} catch (e) {
					uni.showModal({
						title: '录音错误',
						content: '请在app和小程序端体验录音，Uni官方明确H5不支持getRecorderManager, 详情查看Uni官方文档'
					});
				}
			},
			onRecordEnd() {
				var disx = this.endX - this.startX;
				var disy = this.endY - this.startY;

				if (disy + this.startY != 0 && Math.abs(disy) > 50) {
					this.RecordCancel = 1;
				}

				try {
					recorderManager.stop();
				} catch (e) {
					console.log(e);
				}
			},
			onRecordCancel(e) {
				var touch = e.touches[0]
				this.endX = touch.pageX;
				this.endY = touch.pageY;
				console.log("endX:" + this.endX + "," + "endY:" + this.endY);
			},
			showImageFullScreen(e) {
				let imagesUrl = [e.currentTarget.dataset.url];
				uni.previewImage({
					urls: imagesUrl
				});
			},
			//语音录制按钮和键盘输入的切换
			switchAudioKeyboard() {
				this.audio.visible = !this.audio.visible;
				if (uni.authorize) {
					uni.authorize({
						scope: 'scope.record',
						fail: () => {
							uni.showModal({
								title: this.$t('chat.chat_failed_recording'),
								content: this.$t('chat.chat_authorize_recording')
							});
						}
					})
				}
			},
			playVideo(e) {
				this.videoPlayer.visible = true;
				this.videoPlayer.url = e.currentTarget.dataset.url;
				this.$nextTick(() => {
					this.videoPlayer.context.requestFullScreen({
						direction: 0
					});
					this.videoPlayer.context.play();
				});
			},
			onVideoFullScreenChange(e) {
				//当退出全屏播放时，隐藏播放器
				if (this.videoPlayer.visible && !e.detail.fullScreen) {
					this.videoPlayer.visible = false;
					this.videoPlayer.context.stop();
				}
			},
			messageInputFocusin(e) {
				console.log(e)
				this.otherTypesMessagePanelVisible = false;
				this.emoji.visible = false;

			},
			showEmoji() {
				this.emoji.visible = !this.emoji.visible;
				this.otherTypesMessagePanelVisible = false;
			},
			showOtherTypesMessagePanel() {
				this.otherTypesMessagePanelVisible = !this.otherTypesMessagePanelVisible;
				this.emoji.visible = false;
			},
			chooseEmoji(emojiKey) {
				this.content += emojiKey;
			},
			inputContent(e) {
				if (this.content == '') {
					this.changeSendMode = 'add'
				} else {
					this.changeSendMode = 'send'
				}
			},
			createCustomMessage(data) {
				let customMessage = this.goEasy.im.createCustomMessage({
					type: 'order',
					payload: {
						number: data.number,
						goods: data.goods,
						price: data.price
					},
					to: {
						id: this.group.uuid,
						type: this.GoEasy.IM_SCENE.GROUP,
						data: {
							name: this.group.name,
							avatar: this.group.GroupAvatarImg != '' ? this.group.GroupAvatarImg :
								'/static/static/assets/gruopavatar.svg'
						}
					},
					notification: {
						title: this.currentUser.name + '发来一份订单',
						body: '[订单消息]' // 字段最长 50 字符
					}
				});
				this.sendMessage(customMessage);
				this.customMessageFormVisible = false;
			},
			showCustomMessageForm() {
				this.customMessageFormVisible = true;
			},
			closeCustomMessageForm() {
				this.customMessageFormVisible = false;
			},
			scrollToBottom() {
				console.log("下拉了。。。。")
				// const query = uni.createSelectorQuery().in(this);
				// let nodesRef = query.select('#message-scroll');
				// nodesRef.boundingClientRect(res => {
				// 	this.$nextTick(() => {
				// 		//进入页面滚动到底部
				// 	  this.scrollTop = res.height;
				// 		console.log("this.scrollTop", res.height)
				// 	});
				// }).exec()

				this.$nextTick(() => {
					//进入页面滚动到底部
					this.scrollTop = 999999;
				});
			},
			markGroupMessageAsRead(groupId) {

				console.log("zai zhe ");
				console.log("groupId", groupId);
				this.goEasy.im.markGroupMessageAsRead({
					groupId: groupId.toString(),
					onSuccess: function() {
						console.log('标记群聊已读成功');
					},
					onFailed: function(error) {
						console.log('标记群聊已读失败:', error);
					}
				})
			},
			onNavigationBarButtonTap(e) {
				console.log("e.text", e.text);
				if (e.text == 'back') {
					uni.navigateBack()
				} else if (e.type == 'menu') {
					this.$goPage('/note/group/detail', {
						groupId: this.groupId,
						groupName: this.group.GroupName,
						pid: this.pid,
					});
				}
			},
			getHeight(e) {
				this.$nextTick(() => {
					console.log("e.detail.heightRpx", e.detail.heightRpx)
					if (parseInt(this.height) > 316) {
						this.textHeight = e.detail.heightRpx
						return
					}
					this.height = e.detail.heightRpx
				})
			},
			groupMemberAvatar(avatar, userId) {
				if (this.groupMemberDict[userId] && this.groupMemberDict[userId].UserAvatar !=
					'https://idock-1305057061.cos.ap-beijing.myqcloud.com/avatar/2022-06-28/avatar.png') {
					return this.groupMemberDict[userId].UserAvatar
				}
				if (this.groupMemberDict[userId] && this.groupMemberDict[userId].UserAvatar ==
					'https://idock-1305057061.cos.ap-beijing.myqcloud.com/avatar/2022-06-28/avatar.png') {
					return '../../../../static/images/avatar.jpg'
				}
				if (avatar == '') {
					return '../../../../static/images/avatar.jpg'
				}
				if (avatar.indexOf("http") === 0) {
					return avatar
				}
				if (avatar.indexOf("avatar/") === 0) {
					return 'https://idock-1305057061.cos.ap-beijing.myqcloud.com/' + avatar
				}
			},
			messageImageUrl(url) {
				if (url !== '') {
					if (url.indexOf("https://idock.oss-accelerate.aliyuncs.com") === 0) {
						return url + '?x-oss-process=image/resize,h_150'
					}
					return url
				}
			},
			closeDropdown() {
				this.otherTypesMessagePanelVisible = false
				this.emoji.visible = false
				this.isShowTip = false
			},
			// 某文件上传结束回调(成功失败都回调)
			onuploadEnd(item) {
				console.log(`${item.name}已上传结束，上传状态=${item.type}`);

				// 更新当前状态变化的文件
				this.files.set(item.name, item);

				// 演示上传完成后取服务端数据
				if (item['responseText']) {
					console.log('演示服务器返回的字符串JSON转对象');
					this.files.get(item.name).responseText = JSON.parse(item.responseText);
					console.log(this.files.get(item.name).responseText)
				}
				console.log(this.files.values)

				// 微信小程序Map对象for循环不显示，所以转成普通数组，不要问为什么，我也不知道
				// #ifdef MP-WEIXIN
				this.wxFiles = [...this.files.values()];
				// #endif

				// 强制更新视图
				this.$forceUpdate();


				// ---可删除--演示判断是否所有文件均已上传成功
				let isAll = [...this.files.values()].find(item => item.type !== 'success');
				if (!isAll) {
					console.log('已全部上传完毕');
				} else {
					console.log(isAll.name + '待上传');
				}

			},
			// 上传进度回调
			onprogress(item) {
				// 更新当前状态变化的文件
				this.files.set(item.name, item);
				console.log(this.files.values())
				console.log('打印对象', JSON.stringify(this.files.get(item.name)));
				// 微信小程序Map对象for循环不显示，所以转成普通数组，不要问为什么，我也不知道
				// #ifdef MP-WEIXIN
				this.wxFiles = [...this.files.values()];
				// #endif

				// 强制更新视图
				this.$forceUpdate();

			},
			// 文件选择回调
			selectedHandler(ret) { // 组件选择文件回调 返回值 [{path:"文件路径",state:0,size:"文件大小"}...]
				console.log(this.selectList)
				this.selectList = ret

				console.log("seleted", JSON.stringify(ret))
				this.selectList.forEach(file => {
					//文件消息
					let fileMessage = this.goEasy.im.createFileMessage({
						// file: document.getElementById('testFile').files[0], //Html获得file对象
						to: {
							id: this.groupId,
							type: this.GoEasy.IM_SCENE.GROUP,
							data: {
								name: this.group.GroupName,
								avatar: this.group.GroupAvatarImg != '' ? this.group
									.GroupAvatarImg : '/static/static/assets/gruopavatar.svg'
							}
						},
						file: file,
						onProgress: function(progress) {
							console.log(progress)
						},
						notification: {
							title: this.currentUser.uname + this.$t('chat')
								.chat_send_message,
							body: '[' + this.$t('chat.chat_file_message') +
								']' // 字段最长 50 字符
						},

					});
					console.log(fileMessage + "看看这里面封装什么样")
					this.sendMessage(fileMessage);
				})
			},
			selectFileHandler() { // 选择文件方法调用组件的select方法
				// 初始化数据
				this.selectList = []
				this.start = false
				this.$refs.uploads.select()
			},
			// 文件选择回调
			onChange(files) {
				// 更新选择的文件
				this.files = files;
				// 强制更新视图
				this.$forceUpdate();

				// 微信小程序Map对象for循环不显示，所以转成普通数组，不要问为什么，我也不知道
				// #ifdef MP-WEIXIN
				this.wxFiles = [...this.files.values()];
				// #endif
			},
			// 手动上传
			upload() {
				// name=指定文件名，不指定则上传所有type等于waiting和fail的文件
				this.$refs['lsjUpload' + this.tabIndex].upload();
			},
			// 移除某个文件
			clear(name) {
				// name=指定文件名，不传name默认移除所有文件
				this.$refs['lsjUpload' + this.tabIndex].clear(name);
			},
			//图片预览
			previewOpen(e) { 
				this.isShowTip = false //关闭操作提示框
				var param = e
				console.log(param);
				this.$refs.previewImage.open(param); // 传入当前选中的图片地址或序号
				return; //如需测试和uni原生预览差别可注释这两行

				//以下是效果对比相关
				var _this = this;
				uni.showModal({
					title: '请选择',
					content: '请选择使用uni原生图片预览或非原生自定义的图片预览。',
					cancelText: 'uni',
					confirmText: '自定义',
					success: function(res) {
						if (res.confirm) {
							_this.$refs.previewImage.open(param); // 传入当前选中的图片地址或序号
						} else if (res.cancel) {
							uni.previewImage({
								current: param,
								urls: _this.imgs
							});
						}
					}
				});
			},
			go2User(uid) {
				if (this.currentUser.uid != uid) {
					uni.navigateTo({
						url: '/pages/user/index?uid=' + parseInt(uid) + '&groupId=' + this.groupId
					});
				}
			},
		}
	}
</script>
<style lang="scss" scoped>
	.TUI-Emoji-area {
		width: 100vw;
		height: 450rpx;
	}

	.icon-qingchu {
		display: inline-block;
		background-color: #fbfbfc;
		width: 100rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		border-radius: 16rpx;
		position: absolute;
		bottom: 30rpx;
		right: 30rpx;
		margin-right: 20rpx;
		font-size: 70rpx;
		margin-top: 24rpx;
	}

	.icon-biaoqing1 {
		position: absolute;
		bottom: 6rpx;
		right: 130rpx;
		font-size: 60rpx;
	}

	.icon-yuyin- {
		position: absolute;
		bottom: 10rpx;
		left: 6rpx;
		font-size: 56rpx;
	}

	.icon-jianpan {
		position: absolute;
		bottom: 0rpx;
		left: 2rpx;
		font-size: 64rpx;
	}

	.action-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-right: 20rpx ;
		margin-left: 20rpx ;

		.action-item-text {
			color: #6D7174;
			margin-top: 10rpx;
		}

		.icon-xiangce,
		.icon-31paishexuanzhong {
			width: 120rpx;
			height: 120rpx;
			border-radius: 36rpx;
			background-color: #fff;
			display: flex;
			justify-content: center;
			align-items: center;
			border: 1px solid #EEEEEE;

		}

		.icon-xiangce {
			font-size: 54rpx;
		}

		.icon-31paishexuanzhong {
			font-size: 60rpx;
		}

		.icon-wenjianjiatianjia {
			width: 120rpx;
			height: 120rpx;
			border-radius: 36rpx;
			background-color: #fff;
			display: flex;
			justify-content: center;
			align-items: center;
			border: 1px solid #EEEEEE;
			font-size: 60rpx;
		}
	}

	.send-message-btn {
		display: inline-block;
		position: absolute;
		bottom: 24rpx;
		right: 20rpx;
		background-color: #0089FF;
		color: #fff ;
		width: 100rpx ;
		height: 60rpx ;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 10rpx;
	}

	.icon-yuyin- {
		position: absolute;
		bottom: 10rpx;
		left: 24rpx;
		font-size: 56rpx;
	}

	.icon-jianpan {
		position: absolute;
		bottom: 0rpx;
		left: 24rpx;
		font-size: 66rpx;
	}

	.record-input {
		position: absolute;
		bottom: 16rpx;
		left: 104rpx;
	}

	.message-input {
		position: absolute;
		bottom: 16rpx;
		left: 104rpx;
		overflow: scroll;
	}

	.textarea-box {
		width: 440rpx;
		padding: 16rpx;
		overflow-y: auto;
	}

	.mul-btn {
		font-size: 50rpx;
		margin: 0 20rpx;
	}

	.transmit-box {
		width: 400rpx;
		padding-top: 20rpx;
		background-color: #fff;
		border-radius: 20rpx;

		.transmit-box-title {
			padding: 10rpx 20rpx;
			font-size: 30rpx;
		}

		.transmit-box-content {
			padding: 10rpx 20rpx;
			font-size: 26rpx;
		}

		.transmit-box-footer {
			background-color: #f4f4f5;
			font-size: 26rpx;
			padding: 10rpx 20rpx;
			border-bottom-left-radius: 20rpx;
			border-bottom-right-radius: 20rpx;
			color: #a1a3a9;
		}
	}

	.tooltips {
		position: absolute;
		width: 620rpx;
		display: flex;
		flex-wrap: wrap;
		background-color: rgba(27, 31, 35, 0.95);
		padding: 20rpx 0 10rpx 10rpx;
		border-radius: 36rpx;
		z-index: 100000;
		user-select: none;
		-webkit-touch-callout: none;

		&.tooltips-active {
			transition: transform 0.15s ease-in-out 0s;
			transform: scale(1, 1);
		}

		&.tooltips-inactive {
			transition: transform 0s ease-in-out 0s;
			transform: scale(0, 0);
		}

		.opt-item {
			width: 23%;
			height: 110rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			font-size: 26rpx;
			color: #fff;

			.opt-item-text {
				color: #bec0c0;
			}
		}

		.triangle1 {
			position: absolute;
			bottom: -30rpx;
			width: 0;
			height: 0;
			border: 16rpx solid transparent;
			border-top-color: rgba(59, 59, 59, 0.9);
			z-index: 1;
		}

		.triangle2 {
			position: absolute;
			top: -30rpx;
			width: 0;
			height: 0;
			border: 16rpx solid transparent;
			border-bottom-color: rgba(59, 59, 59, 0.9);
			z-index: 1;
		}
	}
</style>
